package com.hj.ipproxy.handler;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.hj.ipproxy.bean.HttpEntity;
import com.hj.ipproxy.bean.ProxyIp;
import com.hj.ipproxy.service.ProxyIpServiceImpl;
import com.hj.tools.list.CollnectionUtil;

public abstract class FetchIpHandler {
	/**
	 * 获取代理IP
	 */
	public Set<ProxyIp> fetchProxyIp(ProxyIpServiceImpl proxyIpSev){
		Set<ProxyIp> ips = new HashSet<ProxyIp>();
		String[] urls = getUrls();
		for (String url : urls) {
			HttpEntity ht = new HttpEntity(url);
			initHttpEntity(ht);
			List<String[]> list = getProxyIps(ht);
			if (CollnectionUtil.isNotEmpty(list)) {
				 doParse(ips, list, proxyIpSev);
			}
		}
		proxyIpSev.finishDoTag();
		return CollnectionUtil.filterSet(ips);
	};
	
	/**
	 * 获取代理IP网站URL集合
	 * @return
	 */
	protected abstract String[] getUrls();
	
	/**
	 * 初始化HttpEntity信息
	 */
	protected abstract void initHttpEntity(HttpEntity ht);
	
	/**
	 * 获取IP代理信息集合
	 * @param ht
	 */
	protected abstract List<String[]> getProxyIps(HttpEntity ht);
	
	/**
	 * 解析网站得到的代理IP
	 */
	protected abstract void doParse(Set<ProxyIp> iplist, List<String[]> list, ProxyIpServiceImpl proxyIpSev);
	
	/**
	 * 检查并过滤填充代理IP信息
	 */
	protected void checkAndFilterProxyIpInfo(ProxyIp pi, Set<ProxyIp> iplist, ProxyIpServiceImpl proxyIpSev){
		if (!proxyIpSev.existsBlackList(pi.getIp()) &&
				!proxyIpSev.existsWhiteList(pi.getIp())) {
			HttpEntity ht = proxyIpSev.checkProxyIp(pi.getIp(), pi.getPort());
			if (ht.isSuccess()) {
				pi.setAddrs(ht.getAddrs());
				pi.setRespTime(ht.getRespTime());
				//iplist.add(pi);
				proxyIpSev.addValidityIp(pi);
			}else{
				pi = null;
			}
		}
	}
}
